import { memo, useEffect, useRef } from "react"
import { Chart } from '@antv/g2'
import { styled } from '@umijs/max'

const Container = styled.div`
  width: 36px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  position: relative;

  .pie {
    width: 36px;
    height: 36px;
  }

  .value {
    position: absolute;
    top: 0;
    left: 0;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: bold;
  }

  .label {
    width: 36px;
    height: 16px;
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 300;
    font-size: 12px;
    color: #828282;
    display: flex;
    align-items: center;
    justify-content: center;
  }
`

export interface PieProps {
  value?: number
  total?: number
  color?: string
  name?: string
}

const Pie: React.FC<PieProps> = props => {
  const divRef = useRef<HTMLDivElement>(null)
  const chart = useRef<Chart>()

  useEffect(() => {
    if (chart.current) {
      chart.current.clear()
      chart.current
        .data([
          {
            name: props.name || '',
            percent: (props.value || 0) / (props.total || 1),
            color: props.color || '#888888',
          },
        ])
        .coordinate({ type: 'radial', innerRadius: 0.8 });

      chart.current
        .interval()
        .encode('x', 'name')
        .encode('y', 1)
        .encode('size', 52)
        .encode('color', 'color')
        .scale('color', { type: 'identity' })
        .style('fillOpacity', 0.05)
        .animate(false);

      chart.current
        .interval()
        .encode('x', 'name')
        .encode('y', 'percent')
        .encode('color', 'color')
        .encode('size', 52)
        .style('radius', 26)
        .axis(false)
        .animate('enter', {
          type: 'waveIn',
          easing: 'easing-out-bounce',
          duration: 1000,
        });

      chart.current.interaction('tooltip', false)

      chart.current.render()
    }
  }, [props.value, chart.current])

  useEffect(() => {
    if (divRef.current && !chart.current) {
      chart.current = new Chart({
        container: divRef.current,
        width: 36,
        height: 36,
        margin: 0,
        padding: 2,
        inset: 0,
      })
    }
  }, [divRef.current])

  return (
    <Container>
      <div ref={divRef} className="pie"></div>
      <div className="value">{props.value || 0}</div>
      <div className="label">{props.name}</div>
    </Container>
  )
}

export default memo(Pie)